//
//  AudioVisualDetailViewController.m
//  HomeIn
//
//  Created by mac on 15/11/9.
//  Copyright © 2015年 ZZP. All rights reserved.
//

#import "AudioVisualDetailViewController.h"
#import "UIImageView+PJ.h"
#import <UIImageView+WebCache.h>
#import "AudioVisualModel.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface AudioVisualDetailViewController ()


@property (nonatomic, retain)UISlider * slider;
@property (nonatomic, retain)UILabel * currentLabel;
@property (nonatomic, retain)UILabel * durationLabel;
@end

@implementation AudioVisualDetailViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:self.model.cover_path] placeholderImage:nil];
    int durationMinute = self.model.duration.intValue / 60;
    int durationSecond = self.model.duration.intValue % 60;
    [self.durationLabel setText:[NSString stringWithFormat:@"%02d:%02d", durationMinute, durationSecond]];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor wheatColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outputDeviceChanged:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClick)];
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:self.model.cover_path] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        [self newMusicInfo];
        // 创建滑动条
        self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0.107 * WIDTH, _backImageView.frame.size.height + _backImageView.frame.origin.y * 2, WIDTH - 2 * 0.107 * WIDTH, 30)];
        [self.slider addTarget:self action:@selector(sliderMethod:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.slider];
        
        // 创建下载按钮
        UIButton * download = [UIButton buttonWithType:UIButtonTypeCustom];
        [download setFrame:CGRectMake(self.slider.frame.origin.x, self.slider.frame.origin.y + self.slider.frame.size.height + 40, 32, 32)];
        [download setImage:[UIImage imageNamed:@"iconfont-xiazai-2.png"] forState:UIControlStateNormal];
        [download addTarget:self action:@selector(downloadClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:download];
        
        
        // 创建播放按钮
        self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.playButton setFrame:CGRectMake(0, 0, 32, 32)];
        [self.playButton setCenter:CGPointMake(WIDTH / 2, download.frame.origin.y + 16)];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-2.png"] forState:UIControlStateNormal];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-5.png"] forState:UIControlStateSelected];
        [self.playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.playButton];
        
        
        // 创建停止按钮
        
        UIButton * stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [stopButton setFrame:CGRectMake(0, 0, 32, 32)];
        [stopButton setCenter:CGPointMake(self.playButton.center.x + (self.playButton.center.x - download.center.x), download.frame.origin.y + 16)];
        [stopButton setImage:[UIImage imageNamed:@"iconfont-tingzhi-2.png"] forState:UIControlStateNormal];
        [stopButton addTarget:self action:@selector(stopButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:stopButton];
        
        // 显示当前时间
        self.currentLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.slider.frame.origin.x, self.slider.frame.size.height + self.slider.frame.origin.y + 5, self.slider.frame.size.width / 2, 15)];
        [self.currentLabel setText:@"00:00"];
        [self.currentLabel setFont:[UIFont systemFontOfSize:13]];
        [self.view addSubview:self.currentLabel];
        
        // 显示全部时间
        self.durationLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.currentLabel.frame.size.width + self.currentLabel.frame.origin.x, self.currentLabel.frame.origin.y, self.slider.frame.size.width - self.currentLabel.frame.size.width, self.currentLabel.frame.size.height)];
        int durationMinute = self.model.duration.intValue / 60;
        int durationSecond = self.model.duration.intValue % 60;
        [self.durationLabel setText:[NSString stringWithFormat:@"%02d:%02d", durationMinute, durationSecond]];
        [self.durationLabel setTextAlignment:NSTextAlignmentRight];
        [self.durationLabel setFont:[UIFont systemFontOfSize:13]];
        [self.view addSubview:self.durationLabel];
    }];
}
- (void)leftButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
// 音乐播放
- (void)playMusic
{
    [self.player play:self.model.play_path_64];
    self.musicTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerWithSlider) userInfo:nil repeats:YES];
}
// 定时器方法: 控制当前时间和slider的当前进度
- (void)timerWithSlider
{
    // 设置slider的最大值
    [self.slider setMaximumValue:self.player.duration];
    // 设置slider的当前值
    [self.slider setValue:self.player.progress];
    // 当播放结束的时候
    if ((int)self.player.progress != 0) {
        if ((int)self.player.progress  > (int)self.player.duration - 1) {
            [self.playButton setSelected:NO];
        }
    }
    
    
    int currentMinute = self.player.progress / 60;
    int currentSecond = (int)self.player.progress % 60;
    [self.currentLabel setText:[NSString stringWithFormat:@"%02d:%02d", currentMinute, currentSecond]];
}
// 滑动滑块
- (void)sliderMethod:(UISlider *)slider
{
    if (self.player) {
        [self.player seekToTime:slider.value];
    }
}
- (void)outputDeviceChanged:(NSNotification *)aNotification

{
    if (self.player.state == STKAudioPlayerStatePlaying) {
//        [self playButtonClick];
        [self.player pause];
        self.playButton.selected = NO;
    }
//    if (self) {
//        <#statements#>
//    }
    NSLog(@"---%@", aNotification.userInfo);
    // do your jobs here
    
}
// 点击下载按钮
- (void)downloadClick
{
    
}






-(void)newMusicInfo
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    [dict setObject:[AudioVisualDetailViewController shareAudioVisualDetailViewComtroller].model.title forKey:MPMediaItemPropertyTitle];
    
    [dict setObject:@"FN" forKey:MPMediaItemPropertyArtist];
    
    [dict setObject:@"推荐" forKey:MPMediaItemPropertyAlbumTitle];
    

    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
}









// 点击播放按钮
- (void)playButtonClick
{
    if (self.playButton.selected == YES) {
        self.playButton.selected = NO;
        [self.player pause];
        [self.musicTimer setFireDate:[NSDate distantFuture]];
    } else {
        self.playButton.selected = YES;
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self.player resume];
            [self.musicTimer setFireDate:[NSDate distantPast]];
        } else {
            [self playMusic];
        }
    }
}
// 点击停止按钮
- (void)stopButtonClick
{
    [self.playButton setSelected:NO];
    [self.player stop];
    [self.player clearQueue];
    self.player = nil;
    self.slider.value = 0.f;
}
- (UIImageView *)backImageView
{
    if (!_backImageView) {
        _backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 2, WIDTH / 2)];
        [_backImageView setCenter:CGPointMake(WIDTH / 2, WIDTH / 2)];
        [_backImageView MasksToBounds:YES CornerRadius:_backImageView.frame.size.width / 2];
        [self.view addSubview:_backImageView];
    }
    return _backImageView;
}
// 创建音乐播放器
- (STKAudioPlayer *)player
{
    if (!_player) {
        _player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){.flushQueueOnSeek=YES, .enableVolumeMixer=YES, .equalizerBandFrequencies={50,100,200,400,800,1600,2600,16000}}];
//        [_player setDelegate:self];
    }
    return _player;
}
+ (instancetype)shareAudioVisualDetailViewComtroller
{
    static AudioVisualDetailViewController * VC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        VC = [[AudioVisualDetailViewController alloc] init];
    });
    return VC;
}
- (void)setSongID:(NSString *)songID
{
    if (_songID != songID) {
        _songID = songID;
        
        [self.player stop];
        [self.playButton setSelected:NO];
    }
}
+ (void)initialize
{
    // 1. 创建音频会话
    AVAudioSession * session = [[AVAudioSession alloc] init];
    // 2. 设置会话类型
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    // 3. 激活会话
    [session setActive:YES error:nil];
    
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
